package org.springframework.samples.mvc.basic.business;

import java.util.ArrayList;
import java.util.List;

import javax.management.relation.Role;

import org.springframework.samples.mvc.basic.model.Identifiable;
import org.springframework.samples.mvc.basic.security.roles.Roles;
import org.springframework.samples.mvc.basic.tipGotovProizvod.ViewDTO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;

import com.proba.annotations.GenericDAO;

public abstract class AbstractBusinessService<T extends Identifiable, V extends ViewDTO<T>> implements BusinessService<V> {
	
	protected abstract GenericDAO<T, Long> getDao();
	protected abstract Transformer<T, V> getTransformer();
	
	@Transactional
	public abstract List<V> findAll(int startIndex, int pageSize, V queryInfo);

	@PreAuthorize("hasRole('"+ Roles.ROLE_SAVE +"')")
	@Transactional
	public void save(V object) {
		getDao().saveOrUpdate(getTransformer().transform(object));
	}

	@Transactional
	public V findById(Long id) {
		T object = getDao().getById(id);
		return  getTransformer().transform(object);
	}

	@Transactional
	public List<V> findAll() {
		List<T> res = getDao().findAll();
		return transform(res);
	}
	
	@Override
	@Transactional
	public List<V> findAll(String orderBy) {
		return transform(getDao().findAll(orderBy));
	}

	@PreAuthorize("hasRole('"+ Roles.ROLE_DELETE +"')")
	@Transactional
	public void delete(Long id) {
		getDao().deleteById(id);
	}

	@Transactional
	public List<V> findAll(int startIndex, int pageSize) {
		List<T> res = getDao().findAll(startIndex, pageSize);
		return transform(res);
	}

	@Transactional
	public int count() {
		int res = getDao().findAll().size();
		return res;
	}
	
	protected List<V> transform(List<T> res) {
		List<V> list = new ArrayList<V>();
		for (T gotovProizvod : res) {
			list.add(getTransformer().transform(gotovProizvod));
		}
		return list;
	}
}
